package edu.hm.swe2.shareit.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;

import edu.hm.swe2.shareit.domain.Email;


public class EmailDAO
{
	private EntityManager emgr = Persistence
			.createEntityManagerFactory("ShareItJPA").createEntityManager();

	public final void create(Email mail)
	{
		emgr.getTransaction().begin();
		emgr.persist(mail);
		emgr.getTransaction().commit();
	}

	public Email read(int id) {
		return emgr.find(Email.class, id);
	}

	public final Email findByEmail(String str)
	{
		emgr.getTransaction().begin();

		TypedQuery<Email> tq =
			emgr.createQuery(
						"select object(e) from Email e where e.email = ?1",
						Email.class);
		tq.setParameter(1, str);

		List<Email> result = tq.getResultList();

		emgr.getTransaction().commit();

		if (result.isEmpty())
		{
			return null;
		} else
		{
			return result.get(0);
		}
	}

	public final void update(Email mail)
	{
		emgr.getTransaction().begin();
		emgr.merge(mail);
		emgr.getTransaction().commit();
	}

	public final void delete(Email mail)
	{
		emgr.getTransaction().begin();
		mail = emgr.merge(mail);
		emgr.remove(mail);
		emgr.getTransaction().commit();
	}
}
